<template>
    <div>
        <app-head :searchInput="searchValue"></app-head>
        <app-body>
            <div style="min-height: 85vh;">
                <div style="margin: 0 20px;padding-top: 20px;">
                    <!-- 搜索结果提示 -->
                    <div v-if="searchValue" class="search-result-header">
                        <h2>搜索结果</h2>
                        <p>搜索 "<span class="keyword">{{ searchValue }}</span>" 的结果：共找到 {{ totalItem }} 件商品</p>
                    </div>
                    
                    <div style="text-align: center;color: #555555;padding: 40px;" v-if="idleList.length===0 && searchValue">
                        <i class="el-icon-search" style="font-size: 48px; color: #ddd; margin-bottom: 20px;"></i>
                        <div style="font-size: 16px;">暂无匹配的商品</div>
                        <div style="font-size: 14px; color: #999; margin-top: 10px;">试试更换关键词或浏览其他商品</div>
                    </div>
                    
                    <el-row :gutter="30" v-if="idleList.length > 0">
                        <el-col :span="6" v-for="(idle,index) in idleList" :key="index">
                            <div class="idle-card" @click="toDetails(idle)">
                                <el-image
                                        class="idle-image"
                                        :src="idle.imgUrl"
                                        fit="cover">
                                    <div slot="error" class="image-slot">
                                        <span class="no-image-text">无图</span>
                                    </div>
                                </el-image>
                                <div class="idle-content">
                                    <div class="idle-title">{{ idle.idleName }}</div>
                                    <div class="idle-description">{{ idle.idlePlace }}</div>
                                    <div class="idle-price">
                                        <span class="price-symbol">￥</span>
                                        <span class="price-number">{{ idle.idlePrice }}</span>
                                    </div>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div class="fenye">
                    <el-pagination
                            background
                            @current-change="handleCurrentChange"
                            :current-page.sync="currentPage"
                            :page-size="8"
                            layout="prev, pager, next, jumper"
                            :total="totalItem">
                    </el-pagination>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'

    export default {
        name: "search",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                idleList: [],
                currentPage: 1,
                searchValue: '',
                totalItem:1
            };
        },
        created() {
            const searchValue = this.$route.query.searchValue;
            const page = parseInt(this.$route.query.page) || 1;
            
            if (searchValue) {
                this.searchValue = searchValue;
                this.currentPage = page;
                this.findIdleTiem(page, searchValue);
            } else {
                this.$message.warning('请输入搜索关键词');
                this.$router.push('/');
            }
        },
        watch: {
            $route(to, from) {
                const searchValue = to.query.searchValue;
                const page = parseInt(to.query.page) || 1;
                
                if (searchValue) {
                    this.searchValue = searchValue;
                    this.currentPage = page;
                    this.findIdleTiem(page, searchValue);
                } else {
                    this.idleList = [];
                    this.totalItem = 0;
                }
            }
        },
        methods: {
            findIdleTiem(page, findValue) {
                if (!findValue || !findValue.trim()) {
                    this.idleList = [];
                    this.totalItem = 0;
                    return;
                }

                const loading = this.$loading({
                    lock: true,
                    text: '搜索中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.1)'
                });

                // 使用现有的API获取所有商品，然后进行搜索过滤
                this.$api.findIdleItemByLable(0, {
                    page: 1,
                    size: 100  // 获取更多数据用于搜索
                }).then(res => {
                    if (res.code === 200 && res.data && res.data.content) {
                        let list = res.data.content;
                        
                        // 过滤只显示状态为approved的商品
                        list = list.filter(item => item.statusCheck === 'APPROVED');
                        
                        // 根据搜索关键词过滤商品
                        const keyword = findValue.toLowerCase();
                        list = list.filter(item => {
                            const name = item.productName ? item.productName.toLowerCase() : '';
                            const description = item.productDescription ? item.productDescription.toLowerCase() : '';
                            return name.includes(keyword) || description.includes(keyword);
                        });
                        
                        // 处理数据格式，适配模板显示
                        for (let i = 0; i < list.length; i++) {
                            // 适配时间格式
                            list[i].timeStr = list[i].createdAt ? 
                                list[i].createdAt.substring(0, 10) + " " + list[i].createdAt.substring(11, 19) : '';
                            
                            // 处理图片
                            let pictureList = list[i].images ? list[i].images.split(',') : [];
                            list[i].imgUrl = pictureList.length > 0 ? pictureList[0] : '';
                            
                            // 适配字段名
                            list[i].idleName = list[i].productName;
                            list[i].idlePrice = list[i].productPrice;
                            list[i].idlePlace = list[i].productDescription;
                            list[i].id = list[i].productID;
                            
                            // 模拟用户信息（如果没有的话）
                            if (!list[i].user) {
                                list[i].user = {
                                    avatar: '',
                                    nickname: '商家'
                                };
                            }
                        }
                        
                        // 实现分页
                        const pageSize = 8;
                        const startIndex = (page - 1) * pageSize;
                        const endIndex = startIndex + pageSize;
                        
                        this.idleList = list.slice(startIndex, endIndex);
                        this.totalItem = list.length;
                        
                        if (list.length === 0) {
                            this.$message.info(`未找到包含 "${findValue}" 的商品`);
                        }
                    } else {
                        this.idleList = [];
                        this.totalItem = 0;
                        this.$message.error('搜索失败');
                    }
                }).catch(err => {
                    console.error('搜索失败:', err);
                    this.idleList = [];
                    this.totalItem = 0;
                    this.$message.error('搜索请求失败，请稍后重试');
                }).finally(() => {
                    loading.close();
                });
            },
            handleClick(tab, event) {
                console.log(tab, event);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.$router.replace({query: {page: val, searchValue: this.searchValue}});
                this.findIdleTiem(val, this.searchValue);
            },
            toDetails(idle) {
                this.$router.push({path: '/details', query: {productId: idle.id}});
            }
        }
    }
</script>

<style scoped>
    .search-result-header {
        margin-bottom: 30px;
        padding-bottom: 20px;
        border-bottom: 1px solid #eee;
    }

    .search-result-header h2 {
        margin: 0 0 10px 0;
        font-size: 24px;
        color: #333;
    }

    .search-result-header p {
        margin: 0;
        color: #666;
        font-size: 16px;
    }

    .keyword {
        color: #409EFF;
        font-weight: 600;
    }

    .idle-card {
        border: 1px solid #e0e0e0;
        border-radius: 10px;
        overflow: hidden;
        cursor: pointer;
        transition: box-shadow 0.3s, transform 0.3s;
        background-color: #fff;
        height: 230px;
        display: flex;
        flex-direction: column;
        margin-bottom: 20px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
    }

    .idle-card:hover {
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
        transform: translateY(-4px);
    }

    .idle-image {
        width: 100%;
        height: 140px;
        object-fit: cover;
        flex-shrink: 0;
    }

    .idle-content {
        flex: 1;
        padding: 12px 14px;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        gap: 4px;
    }

    .idle-title {
        font-size: 20px;
        font-weight: 700;
        color: #222;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        line-height: 1.3;
    }

    .idle-description {
        font-size: 13px;
        color: #888;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        line-height: 1.2;
    }

    .idle-price {
        margin-top: auto;
        font-size: 22px;
        color: #f44336;
        font-weight: bold;
        line-height: 1;
        margin-top: 1px;
        display: flex;
        align-items: baseline;
    }

    .price-symbol {
        font-size: 16px;
        color: #f44336;
        font-weight: bold;
        margin-right: 2px;
    }

    .price-number {
        font-size: 22px;
        color: #f44336;
        font-weight: bold;
    }

    .image-slot {
        width: 100%;
        height: 100%;
        background-color: #f5f5f5;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .no-image-text {
        color: #999;
        font-size: 14px;
        font-weight: 500;
    }

    .fenye {
        display: flex;
        justify-content: center;
        height: 60px;
        align-items: center;
    }
</style>